package com.beiding.service;


import com.beiding.dao.MessageDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {


    private SimpMessagingTemplate template;

    private MessageDao dao;

    @Autowired
    public void setDao(MessageDao dao) {
        this.dao = dao;
    }

    @Autowired
    public void setTemplate(SimpMessagingTemplate template) {
        this.template = template;
    }

    @Override
    public void offline(String name) {
        dao.removeOnlineUser(name);
    }

    @Override
    public void online(String name) {

        //添加一个上线的用户
        dao.addOnlineUser(name);
    }

    @Override
    public void send(String receiver, String topic, String payload) {

        //首先在发送前先去检查用户是否已经上线,如果上线就直接发送,如果没有上线就把消息放在数据库中,等上线的时候再推送给用户

            template.convertAndSendToUser(receiver, "/queue/"+topic, payload);


            /*if (dao.isOnline(receiver)) {
        } else {
            dao.saveMessage(receiver, "/queue/"+topic, payload);
        }*/

    }

    @Override
    public void subscribe(String user, String destination) {

        if (destination.startsWith("/user")) {
            destination = destination.substring(5);
        }

        //获取未上线时期存储的消息
        List<String> ms = dao.getAndRemoveMessages(user, destination);

        //保留最后的最多三条消息

        if (ms != null) {


            final int size = ms.size();

            if (size > 3) {
                ms.subList(0, size - 3).clear();
            }


            for (String s : ms) {
                template.convertAndSendToUser(user, destination, s);
            }
        }

    }


}
